package com.yonyou.pmclouds.discuss.impl;

import com.yonyou.pmclouds.basecom.bp.processor.AuditInfoInsertProcessor;
import com.yonyou.pmclouds.basecom.bp.template.SingleInsertBpTemplate;
import com.yonyou.pmclouds.basecom.entity.KeyCountVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.CommonProgramConsts;
import com.yonyou.pmclouds.discuss.entity.DiscussionVO;
import com.yonyou.pmclouds.discuss.itf.DiscussInternalOperation;
import com.yonyou.pmclouds.discuss.mapper.DiscussionMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DiscussInternalOperationImpl implements DiscussInternalOperation {
    @Autowired
    private DiscussionMapper mapper;

    @Override
    public DiscussionVO queryByDiscussId(String discussId) {
        if (StringUtils.isEmpty(discussId)) {
            return null;
        }
        return mapper.getById(discussId);
    }

    @Override
    public DiscussionVO[] queryByRelateId(String relateKey, String pkTenant) {
        return mapper.queryByRelateKey(relateKey);
    }

    @Override
    public void insertDiscussion(DiscussionVO discussion) throws BusinessException {
        SingleInsertBpTemplate<DiscussionVO> bp = new SingleInsertBpTemplate<>(mapper);
        bp.addBeforeProcessor(new AuditInfoInsertProcessor<DiscussionVO>());
        bp.insert(discussion);
    }

    @Override
    public Map<String, Integer> countDiscussion(String[] keys) throws BusinessException {
        if (ArrayUtils.isEmpty(keys)) {
            return null;
        }
        if (keys.length > CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE) {
            keys = ArrayUtils.subarray(keys, 0, CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE);
        }
        KeyCountVO[] keyCounts = mapper.countByRelateKeys(keys);
        if (ArrayUtils.isEmpty(keyCounts)) {
            return null;
        }
        Map<String, Integer> result = new HashMap<>(keyCounts.length);
        for (KeyCountVO count : keyCounts) {
            result.put(count.getRelateKey(), count.getKeyNum());
        }
        return result;
    }

    @Override
    public void deleteDiscussion(String discussId) {
        mapper.delete(discussId);
    }
    // 暂时不需要修改
}
